package com.oa.tools.jobs.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Node;
import org.springframework.beans.BeanUtils;

import com.oa.tools.TkMapper;
import com.oa.tools.entity.FlowLog;
import com.oa.tools.entity.OAFlowInstanceWithBLOBs;
import com.oa.tools.entity.OrgElementWithPerson;
import com.oa.tools.entity.Person;
import com.oa.tools.jobs.FlowHandlerTaskBase;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.SysConfig;
import com.oa.tools.utils.XmlUtil;

import tk.mybatis.mapper.entity.Example;

public class AddNewPeopleTask extends FlowHandlerTaskBase{

	
	public AddNewPeopleTask(Map<String,TkMapper<?>> daoMap) {
		super(daoMap);
		
		this.flowStatus = FlowHandlerTaskBase.FLOW_STATUS_ING;
		this.templateId = "1601f2ce30513e8c16f6d9f44e598885";
		
		//,ProcessBase.FLOW_STATUS_ING, "新入职人员办理", new String[] {"入职办理"}
	}

	@Override
	public String exec(boolean notice, OAFlowInstanceWithBLOBs obj) throws Exception {
		String fdId = obj.getFdId();
		Example example_log = new Example(FlowLog.class);
		example_log.createCriteria().andEqualTo("fdProcessId", fdId).andEqualTo("fdFactNodeId", "N35");
		List<FlowLog> flowLogs = this.flowLogDAO.selectByExample(example_log);
		if(flowLogs==null || flowLogs.size()==0) {
			return null;
		}else {
			for(FlowLog flowLog:flowLogs) {
				if(!flowLog.getFdStatus().equals(FlowHandlerTaskBase.FLOW_STATUS_DONE)) {
					return null;
				}
			}
		}
		
		String xmlStr = obj.getExtendDataXml();
//		System.out.println(xmlStr);

//		Object [] result = EKPRequestClient.createNewStaffAccountCore(xmlStr, obj.getFdId(),orgElementDAO);
		List<Map<String,String>> peopleMaps = new ArrayList<>();
		Map<String,String> tableMap = SysConfig.getMap("新入职流程处理配置", "新入职字段");
		String result_new_xmlstr = XmlUtil.parseXml2StaffMap(xmlStr, (String) tableMap.get("明细表"),
				new XmlUtil.XMLHandler() {
					public void hanle(Node staff_node) throws Exception {
						List<Node> staff_ele_nodes = staff_node.selectNodes("void");
						Node emailnode = null;
						Node lognode = null;
						Node namenode = null;
						Node mobilnode = null;
						String tel = "";
						Map<String,String> peopleMap = new HashMap<String,String>();
						for (Node staff_ele_node : staff_ele_nodes) {
							String key = staff_ele_node.selectSingleNode("string[1]").getText();

							Node node = staff_ele_node.selectSingleNode("string[2]");
							String value = "";
							if (node == null) {
								node = staff_ele_node.selectSingleNode("object/long");
								if (node == null) {
									node = staff_ele_node.selectSingleNode("null");
									if (node == null) {
										node = staff_ele_node.selectSingleNode("object/void[2]/string[2]");
									}
								}
							}
							if (node != null) {
								value = node.getText();
							}
							if (((String) tableMap.get("手机")).equals(key)) {
								mobilnode = node;
								peopleMap.put("手机", value);
							}else if (((String) tableMap.get("邮箱")).equals(key)) {
								emailnode = node;
								peopleMap.put("邮箱", value);
							}else if (((String) tableMap.get("登录名")).equals(key)) {
								lognode = node;
							}else if (((String) tableMap.get("姓名")).equals(key)) {
								namenode = node;
								peopleMap.put("姓名", value);
							}else if (((String) tableMap.get("工号")).equals(key)) {
								peopleMap.put("工号", value);
							}else if (((String) tableMap.get("座机")).equals(key)) {
								peopleMap.put("座机", value);
								tel = value;
							}else if (((String) tableMap.get("部门")).equals(key)) {
								peopleMap.put("部门", value);
							}else if (((String) tableMap.get("岗位")).equals(key)) {
								peopleMap.put("岗位", value);
							}

						}
						
						peopleMaps.add(peopleMap);
						
						String mobile = mobilnode.getText();
						OrgElementWithPerson person = orgElementWithPersonDAO.selectOneOrgWithPerson(mobile );
						
						if(!tel.equals(person.getFdWorkPhone())) {
							Person p = new Person();
							BeanUtils.copyProperties(person, p);
							tel = tel == null ? "" : (tel.replaceAll("[^\\d]+", "").trim());
							if (tel.length() == 4) {
								tel = "6629" + tel;
							}
							p.setFdWorkPhone(tel);
							personDAO.updateByPrimaryKeySelective(p);
						}
						
						emailnode.setName("string");
						emailnode.setText(person.getFdEmail());
						lognode.setName("string");
						lognode.setText(person.getFdLoginName());
					}
					
		});
		
		
		obj.setExtendDataXml(result_new_xmlstr);
		this.oAFlowInstanceDAO.updateByPrimaryKeySelective(obj);//updateByPrimaryKeyWithBLOBs(obj);

		StringBuilder mailContent = new StringBuilder();
		mailContent.append("<pre>新员工入职办理成功日志如下：\r\n");
		mailContent.append("流程主题：");
		mailContent.append(obj.getDocSubject());
		mailContent.append("\r\n流程ID：");
		mailContent.append(obj.getFdId());
		mailContent.append("\r\n查看详情：");
		mailContent.append("<a href='http://oa.fengbangleasing.com/km/review/km_review_main/kmReviewMain.do?method=view&fdId="+obj.getFdId()+"' >"+obj.getDocSubject()+"</a>");
		mailContent.append("\r\n");
		mailContent.append("</pre><br/>");
		String [] titles = null;
		mailContent.append("<table>");
		for(Map<String,String> peopleMap:peopleMaps) {
			if(titles==null) {
				titles = peopleMap.keySet().toArray(new String[0]);
				mailContent.append("<thead><tr>");
				for(String title:titles) {
					mailContent.append("<td>");
					mailContent.append(title);
					mailContent.append("</td>");
				}
				mailContent.append("</tr></thead>");
				mailContent.append("<tbody><tr>");
			}
			
			mailContent.append("<tr>");
			for(String title:titles) {
				mailContent.append("<td>");
				mailContent.append(peopleMap.get(title));
				mailContent.append("</td>");
			}
			mailContent.append("</tr>");
			
		}
		mailContent.append("</tbody>");
		
		String content = mailContent.toString();

		if (true) {
			String [] receiveMailAccounts = SysConfig.getSysSet("邮箱管理员接收邮箱").toArray(new String[0]);
			MailUtil.sendMail(receiveMailAccounts,
					"新员工入职办理流程处理通知", content);
		}

		return content;
	}

	
}
